# 导包
import pymysql

# 创建工具类
class DButil():
    # 初始化
    __conn = None
    __cursor = None
    # 创建连接
    @classmethod
    def get_conn(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",password="root",database="books")
        return cls.__conn
    # 获取游标
    @classmethod
    def get_cursor(cls):
        if cls.__cursor is None:
            cls.__cursor = cls.get_conn().cursor()
        return cls.__cursor

    @classmethod
    def close_cursor(cls):
        if cls.__cursor is not None:
            cls.__cursor.close()
            cls.__cursor = None

    @classmethod
    def close_conn(cls):
        if cls.__conn is not None:
            cls.__conn.close()
            cls.__conn = None

    # 执行sql语句
    @classmethod
    def exe_sql(cls,sql):
        try:
            # 获取游标对象
            cursor = cls.get_cursor()
            # 调用游标对象.execute(sql)
            cursor.execute(sql)
            # 判断如果是查询操作
            if sql.split()[0].lower() == "select":
                # 返回的是查询数据
                return cursor.fetchall()
            # 非查询操作(新增、修改、删除)
            else:
                 # 提交事务
                cls.__conn.commit()
                # 返回受影响的行数
                return cursor.rowcount
        except Exception as e:
            # 事务回滚
            cls.__conn.rollback()
            print(e)
        finally:
            cls.close_cursor()
            cls.close_conn()



